package com.lang.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminFilter extends BaseFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Object user = request.getSession().getAttribute("admin");
        if (user != null) {
            filterChain.doFilter(request, response);
            return;
        }


        String uri = request.getRequestURI();
        String action = request.getParameter("action");
        if (uri.endsWith("login.jsp") || "login".equals(action)) {
            filterChain.doFilter(request, response);
            return;
        }

        response.sendRedirect("/admin/login.jsp");
    }
}
